<template>
  <div>
    <FilterTable
      ref="basetable"
      :columns="tableColumns"
      :dataSource="tableList"
      selectionType="single"
      :datakey="'rows'"
      :onRowSelectChange="handleRowSelectChange"
      :onColumnsChange="columns => (this.tableColumns = columns)"
    >
      <!-- 执行出库 -->
      <BaseDialog :visible.sync="quertDecorativePartsOut" title="执行出库" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
        <editDecorativePartsOut :billNo="checkbillNo" @close="quertDecorativePartsOut = false" />
      </BaseDialog>
      <!-- 执行退库 -->
      <BaseDialog :visible.sync="quertDecorativePartsReturn" title="执行退库" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
        <editDecorativePartsReturn :billNo="checkbillNo" @close="quertDecorativePartsReturn = false" />
      </BaseDialog>
    </FilterTable>
    <div
      :style="{
        position: 'absolute',
        left: 0,
        bottom: 0,
        right: 0,
        zIndex: 9,
        borderTop: '1px solid #e9e9e9',
        padding: '10px 20px',
        background: '#fff',
        textAlign: 'right'
      }"
    >
      <el-button @click="closeDrawer(1)">取 消</el-button>
      <el-button type="primary" @click="handleOut">执行出库</el-button>
      <el-button type="primary" @click="handleReturn">执行退库</el-button>
      <!-- <el-button type="primary" @click="closeDrawer(2)">保 存</el-button> -->
    </div>
  </div>
</template>
<script>
import { save } from '@/api/part/inventoryManager/inventoryManager/index';
import { editOutStockQuantity, editReturnStockQuantity } from '@/api/part/qualityManagement/decorativePartsExit/index.js';
import { dictionary } from '@/utils/dictMixin';
import { messageAction } from '@/utils';
import pinyin, { STYLE_FIRST_LETTER } from '@/components/Pinyin/index';
import { findAllRepair } from '@/api/repair/basicParameters';
import editDecorativePartsOut from './editDecorativePartsOut';
import editDecorativePartsReturn from './editDecorativePartsReturn';
import { getDecorativePartOutIn, getDecorativePartInfo, checkStockByPartNo } from '@/api/part/qualityManagement/decorativePartsExit';
export default {
  components: {
    editDecorativePartsOut,
    editDecorativePartsReturn
  },
  mixins: [dictionary],
  props: ['getdata'],
  data() {
    this.basetable = null;
    return {
      formList: this.createFrom(),
      quertDecorativePartsOut: false, // 是否显示执行出库
      quertDecorativePartsReturn: false, // 是否显示执行退库
      partInfoList: [],
      commitData: {},
      tableList: [],
      selectedOrderList: [], // 选中的订单列表
      checkbillNo: '', // 获取装饰派工单代码
      tableColumns: this.createTable()
    };
  },
  // computed: {
  //   salerPrice() {
  //     return this.formList.find(item => item.fieldName == 'salesPrice').initialValue;
  //   }
  // },
  // watch: {
  //   salerPrice: function(newVal, oldVal) {
  //     this.formList.find(item => item.fieldName == 'nodePrice').initialValue = newVal;
  //   }
  // },
  // created() {
  //   this.getDictlist();
  // },
  mounted() {
    this.basetable = this.$refs.basetable.$refs.pageTable;
  },
  created() {
    this.initQueryList();
  },
  methods: {
    async queryEmptyLocation(val) {
      let res = await getPosition({ storageCode: val });
      if (res.resultCode === 200) {
        this.formList.find(item => item.fieldName === 'storageCode').itemList = res.data.map(x => ({ text: x.storageCode, value: x.storageCode }));
      }
    },
    initData() {},

    initQueryList() {
      this.tableList = this.getdata;
    },

    createFrom() {
      return [
        // {
        //   type: 'SELECT',
        //   label: '仓库',
        //   fieldName: 'storageCode',
        //   placeholder: '请选择',
        //   disabled: true,
        //   itemList: [],
        //   change: this.queryEmptyLocation
        // },
        // {
        //   type: 'INPUT',
        //   label: '税率',
        //   fieldName: 'taxRate',
        //   initialValue: '',
        //   disabled: true
        // }
      ];
    },
    createTable() {
      return [
        {
          title: '装饰派工单号',
          dataIndex: 'billNo'
        },
        {
          title: '仓库代码',
          dataIndex: 'storageCode'
        },
        {
          title: '仓库名称',
          dataIndex: 'storageName'
        },
        {
          title: '出库状态',
          dataIndex: 'status',
          render: params => {
            return <span>{this.createDictText(params.row.status, '9707')}</span>;
          }
        },
        {
          title: '出库方式',
          dataIndex: 'outType',
          // editType: 'select',
          // editable: true,
          // defaultEditable: true,
          // editItems: this.createDictList(8096)
          render: params => {
            return <span>{this.createDictText(params.row.outType, '8096')}</span>;
          }
        },
        {
          title: '装饰件代码',
          dataIndex: 'partNo'
        },
        {
          title: '装饰件名称',
          dataIndex: 'partName',
          showOverflowTooltip: true
        },
        {
          title: '派工数量',
          dataIndex: 'partQuantity',
          precision: 2,
          sorter: true
        },
        {
          title: '出库数量',
          dataIndex: 'outQuantity',
          precision: 2,
          sorter: true
          // editable: true,
          // defaultEditable: true,
          // editType: 'number',
          // editDisableRender: params => {
          //   return <el-input value={params.row.outQuantity}></el-input>;
          // }
        },
        {
          title: '出库单价',
          dataIndex: 'costOutPrice',
          precision: 2,
          sorter: true
        },
        {
          title: '出库金额',
          dataIndex: 'outTotalPrice',
          precision: 2,
          sorter: true,
          render: props => {
            props.row.outTotalPrice = (Number(props.row.outQuantity) * Number(props.row.costOutPrice)).toFixed(2);
            return <span>{props.row.outTotalPrice}</span>;
          }
        },
        {
          title: '退库数量',
          dataIndex: 'returnQuantity',
          editable: true,
          defaultEditable: true,
          editType: 'number',
          editDisableRender: params => {
            return <el-input value={params.row.returnQuantity}></el-input>;
          },
          precision: 2,
          sorter: true
        },
        {
          title: '可退库数量',
          dataIndex: 'canReturnQuantity',
          precision: 2,
          sorter: true
        }
      ];
    },
    handleRowSelectChange(e) {
      this.selectedOrderList = e;
    },
    changeHandle(val) {
      console.log(val);
      this.commitData = val;
    },
    async closeDrawer(type) {
      if (type == 1) {
        this.$emit('close', false);
      } else {
        this.commitData = this.$refs.form.SUBMIT_FORM();
        this.commitData['flg'] = 'U';

        let obj = { dmstable: [this.commitData], dmsTable: [this.commitData] };
        // obj = JSON.parse(JSON.stringify(obj));
        let res = await save(obj);
        if (res.resultCode == '200') {
          this.$notify.success({ title: '提示信息', message: '保存成功' });
          this.$emit('addChange');
        }
      }
    },
    handleOut() {
      if (this.selectedOrderList.length) {
        this.checkbillNo = this.selectedOrderList[0].billNo;
        let { outQuantity, partQuantity, partNo, storageCode, id, outType } = this.selectedOrderList[0];

        if (outQuantity > partQuantity) {
          messageAction('出库数量不得大于派工数量', 'warning');
        } else if (partQuantity == 0) {
          messageAction('当前装饰件派工数量为0，无法出库', 'warning');
        } else if (outQuantity == partQuantity) {
          messageAction('当前装饰件已出库，请重新选择', 'warning');
        } else {
          this.$confirm('是否确认出库？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            outQuantity = partQuantity; // 将派工数量赋给出库数量
            this.editOutSave(id, partNo, this.checkbillNo, outQuantity, storageCode, outType);
          });
        }

        // editOutStockQuantity
        console.log(this.checkbillNo);
        this.quertDecorativePartsOut = true;
      } else {
        messageAction('请选择需要操作的装饰件', 'warning');
      }
    },
    // 后台保存
    async editOutSave(id, partNo, checkbillNo, outQuantity, storageCode, outType) {
      let checkRes = await checkStockByPartNo({
        storageCode: storageCode,
        partNo: partNo,
        outQuantity: outQuantity
      });
      if (checkRes.resultCode == 200) {
        if (!checkRes.data.result) {
          this.$notify.warning({ title: '提示信息', message: checkRes.data.msg });
          return;
        }
      }

      let res = await editOutStockQuantity({
        id: id,
        partNo: partNo,
        checkbillNo: checkbillNo,
        outQuantity: outQuantity,
        outType: outType
      });
      if (res.resultCode == 200) {
        // this.r3LogList = res.data;
        if (res.data == 'Success') {
          messageAction('出库成功', 'success');
          this.queryBillPartList(checkbillNo);
        } else {
          messageAction('出库失败', 'error');
        }
      }
    },
    // 点击退库
    handleReturn() {
      if (this.selectedOrderList.length) {
        this.checkbillNo = this.selectedOrderList[0].billNo;
        let outQuantity = this.selectedOrderList[0].outQuantity;
        let returnQuantity = this.selectedOrderList[0].returnQuantity;
        let canReturnQuantity = this.selectedOrderList[0].canReturnQuantity; // 可退数量
        let partNo = this.selectedOrderList[0].partNo;
        let id = this.selectedOrderList[0].id;
        console.log(this.checkbillNo, outQuantity, returnQuantity, partNo);
        if (returnQuantity > outQuantity) {
          messageAction('退库数量不得大于出库数量', 'warning');
        } else if (canReturnQuantity == 0) {
          messageAction('当前无可退库装饰件，请重新选择', 'warning');
        } else {
          this.$confirm('是否确认退库？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            console.log;
            this.editReturnSave(id, partNo, this.checkbillNo, returnQuantity);
          });
        }

        // editOutStockQuantity
        console.log(this.checkbillNo);
      } else {
        messageAction('请选择需要操作的装饰件', 'warning');
      }
    },
    // 后台保存
    async editReturnSave(id, partNo, checkbillNo, returnQuantity) {
      let res = await editReturnStockQuantity({
        id: id,
        partNo: partNo,
        checkbillNo: checkbillNo,
        returnQuantity: returnQuantity
      });
      if (res.resultCode == 200) {
        // if (res.data.message == 'Success') {
        messageAction('出库成功', 'Success');
        this.queryBillPartList(checkbillNo);
        // } else {
        //   messageAction('出库失败', 'Error');
        // }
      }
    },
    async queryBillPartList(billNo) {
      let res = await getDecorativePartInfo({ billNo: billNo });
      if (res.storageCode == 200) {
        res.data.map(item => {
          item.outType = item.outType * 1 || '';
        });
      }
      let obj = {};
      console.log('queryBillPartList');
      console.log(res.data);
      this.tableList = res.data;
    },
    changePartName(val) {
      console.log(val, this.partInfoList, 'this.partInfoList');
      let is = false;
      for (let i = 0; i < this.partInfoList.length; i++) {
        if (this.partInfoList[i].value == val) {
          is = true;
        }
      }
      if (is) {
        this.$confirm('配件代码重复是否确定？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {})
          .catch(() => {
            this.formList[8].initialValue = '';
          });
      }
    }
  }
};
</script>
<style lang="less" scoped>
.test {
  text-align: left;
  color: red;
  display: block;
  float: left;
}
</style>
